/*
* Copyright (c)  2017, ueboot.com
* All rights reserved.
* 2017-11-05 17:53:32
*/
package com.ueboot.weishop.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.repository.BaseRepository;
import com.ueboot.core.service.impl.BaseServiceImpl;
import com.ueboot.core.utils.HttpClientUtil;
import com.ueboot.weishop.entity.lottery.LotteryRecordEntity;
import com.ueboot.weishop.entity.order.OrderEntity;
import com.ueboot.weishop.entity.order.OrderIssueEntity;
import com.ueboot.weishop.repository.lottery.LotteryRecordRepository;
import com.ueboot.weishop.repository.order.OrderIssueRepository;
import com.ueboot.weishop.repository.order.OrderRepository;
import com.ueboot.weishop.service.order.OrderIssueService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ziv  on 2017-11-05 17:53:32.
 *
 * @author ziv
 * @since 2.0 by autocode
 */
@Slf4j
@Service
public class OrderIssueServiceImpl extends BaseServiceImpl<OrderIssueEntity> implements OrderIssueService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private OrderIssueRepository orderIssueRepository;

	@Autowired
	private LotteryRecordRepository lotteryRecordRepository;

	@Autowired
	private OrderRepository orderRepository;

	@Override
	protected BaseRepository getBaseRepository() {
		return orderIssueRepository;
	}

	@Override
	public List<OrderIssueEntity> findBySendDmsStatus(String sendDmsStatus) {
		return orderIssueRepository.findBySendDmsStatus(sendDmsStatus);
	}


	@Value("${dms.server}")
	private String dmsServer;

	@Override
	public String sendDmsCoupon(List<Map<String, String>> contentList) {
		Map mapReq = new HashMap();
		mapReq.put("contentList",contentList);
		String requestJson = JSON.toJSONString(mapReq);
		logger.info("发送DMS代金券发送请求：{}", requestJson);
		try {
			if(StringUtils.isEmpty(dmsServer)){
				logger.error("dmsServer为空，不执行业务处理");
				return null;
			}
			String responseMessage = HttpClientUtil.postJSON(dmsServer, requestJson);
			logger.info("发送DMS代金券响应：{}", responseMessage);
			return responseMessage;
		} catch (Exception e) {
			logger.error("调用DMS服务异常！WS不做任何处理！{}", e);
			throw new BusinessException("DMS回传接口服务异常！WS不做任何处理！");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 30, propagation = Propagation.REQUIRED)
	public void updateAll(List<OrderIssueEntity> issueList) {
		orderIssueRepository.save(issueList);
	}

	@Override
	public OrderIssueEntity findTopBySeqNo(String seqNo) {
		return orderIssueRepository.findTopBySeqNoOrderByFirstInsertDesc(seqNo);
	}

	@Override
	public Page<OrderIssueEntity> findByReq(Pageable pageable, OrderIssueEntity params, Date startTime, Date endTime) {
		OrderIssueEntity entity = new OrderIssueEntity();
		ExampleMatcher example = ExampleMatcher.matching().withIgnoreNullValues()
				.withIgnorePaths("lowestAmount", "useAmount", "limitDeduct", "sendDmsStatus", "cancel");
		if (StringUtil.isNotBlank(params.getBatchNo())) {
			entity.setBatchNo(params.getBatchNo());
			example.withMatcher("batchNo", matcher -> matcher.exact());
		}
		if (StringUtil.isNotBlank(params.getSeqNo())) {
			entity.setSeqNo(params.getSeqNo());
			example.withMatcher("seqNo", matcher -> matcher.exact());
		}
		Page<OrderIssueEntity> pages = null;
		if (null != startTime && null != endTime) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startTimeStr = sdf.format(startTime);
			String endTimeStr = sdf.format(endTime);
			List<OrderIssueEntity> listOld = null;
			listOld = orderIssueRepository.findAllOrderIssueEntityByTime(startTimeStr, endTimeStr);
			List<OrderIssueEntity> list = new ArrayList<OrderIssueEntity>();
			for (OrderIssueEntity oie : listOld) {
				Boolean addFlag = true;
				if (StringUtil.isNotBlank(params.getBatchNo())) {
					if (StringUtils.isNotBlank(oie.getBatchNo()) && !oie.getBatchNo().equals(params.getBatchNo())) {
						addFlag = false;
					}
				}
				if (StringUtil.isNotBlank(params.getSeqNo())) {
					if (StringUtils.isNotBlank(oie.getSeqNo()) && !oie.getSeqNo().equals(params.getSeqNo())) {
						addFlag = false;
					}
				}
				if (addFlag) {
					list.add(oie);
				}
			}
			Integer total = list.size();
			Integer pageSize = pageable.getPageSize();
			Integer pageNo = pageable.getPageNumber();
			int startIndex = pageSize * pageNo;
			list = list.subList(startIndex, (startIndex + 10) < total ? startIndex + 10 : total);
			pages = new PageImpl<OrderIssueEntity>(list, pageable, total);
		} else {
			pages = orderIssueRepository.findAll(Example.of(entity, example), pageable);
		}
		return pages;
	}

	@Override
	public List<OrderIssueEntity> findBySendDmsStatusAndCancelAndSendSmsStatus(String sendDmsStatus, String cancer, String sendSmsStatus) {
		return orderIssueRepository.findBySendDmsStatusAndCancelAndSendSmsStatus(sendDmsStatus, cancer, sendSmsStatus);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 30, propagation = Propagation.REQUIRED)
	public void saveIssueUpdateOrderAndLottery(List<OrderIssueEntity> issueList, List<LotteryRecordEntity> lotteryRecordList, List<OrderEntity> orderList) {
		orderIssueRepository.save(issueList);
		lotteryRecordRepository.save(lotteryRecordList);
		orderRepository.save(orderList);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 30, propagation = Propagation.REQUIRED)
	public void save(List<OrderIssueEntity> issueList) {
		orderIssueRepository.save(issueList);
	}

	@Override
	public List<OrderIssueEntity> findByOrderNo(String orderNo) {
		return orderIssueRepository.findByOrderNo(orderNo);
	}
}
